<?php
/**
 * 菜单
 * */
namespace app\common\model;
use think\Model;
use think\Db;


class Menu extends Model
{
    private $cache = 1;   // 缓存60s

    /**
     * 查询Auth数据 并且缓存
     * @return array;
     */
    public function menuData(){
        $order = 'sort asc';
        $res = db('menu')->cache($this->cache)->order($order)->select();
        return $res;
    }

    /**
     * 删除菜单
     * @param $id int;
     * @return int  1成功，0失败
     * */
    public function menuDelete($id){
        $res = db('menu')->delete($id);
        return $res;
    }

    /**
     * 数组转换，把数据id放入到数组键名
     * @return $result = array('id'=>array('id'=>''),'id'=>array('id'=>''));
     * */
    public function dataFormat(){
        $arr = $this->menuData();
        foreach($arr as $k=>$v){
            $result[$v['id']]  = $this->menuDataFormat($v);
        }
        return $result;
    }


    /**
     * 格式化数据
     * @param  $data 多维数组
     * */
    public function menuDataFormat($data){
        $result['id']                                 = $data['id'];
        $result['parent_id']                      = $data['parent_id'];
        $result['name']                            = $data['name'];
        $result['title']                               = $data['title'];
        $result['type']                              = $data['type'];
        $result['is_show']                        = $data['is_show'];
        $result['css']                               = $data['css'];
        $result['sort']                              = $data['sort'];
        $result['is_delete']                       = $data['is_delete'];
        $result['add_time']                       = $data['add_time'];
        return $result;
    }

    /**
     * 条件查询菜单
     * */
    public  function menuWhere($parent_id=0,$type=1,$is_show=1){
        $where['type'] = $type;
        $where['is_show'] = $is_show;
        $where['parent_id'] = $parent_id;
        $order = 'sort asc';
        $res = db('menu')->where($where)->cache($this->cache)->order($order)->select();

        // 格式化数据
        foreach($res as $k=>$v){
            $result[$k] = $this->menuDataFormat($v);
         }

        return $res;
    }

    /**
     * 获取子分类
     * @return array;
     * */
    public function menuParent($parent_id){
        $result = $this->menuWhere($parent_id);
        return $result;
    }

    /**
     * 后台菜单
     * @return array;
     * */
    public function menuAdmin(){
        $arr = $this->menuWhere();
        // 子分类
        foreach($arr as $k=>$v){
            $arr[$k]['child'] = $this->menuParent($v['id']);
        }
        return $arr;
    }

    /**
     * 前台菜单
     * @return array;
     * */
    public function menuIndex(){
        $arr = $this->menuWhere(0,2);
        // 子分类
        foreach($arr as $k=>$v){
            $arr[$k]['child'] = $this->menuParent($v['id']);
        }
        return $arr;
    }


    public function ss(){
        return '87878';
    }

}